package com.github.byakkili.bim.protocol.json.tcp;

import com.github.byakkili.bim.core.BimSession;
import com.github.byakkili.bim.core.handler.command.CommandFrame;
import com.github.byakkili.bim.protocol.json.BaseJsonCodec;
import com.github.byakkili.bim.protocol.json.JsonHelper;
import com.github.byakkili.bim.core.support.util.BimSessionUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.List;
import java.util.Map;

/**
 * @author Guannian Li
 */
@Sharable
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TcpJsonCodec extends BaseJsonCodec<ByteBuf> {
    /**
     * 单例
     */
    public static final TcpJsonCodec INSTANCE = new TcpJsonCodec();

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) {
        BimSession session = BimSessionUtils.get(ctx.channel());

        int command = byteBuf.readInt();
        byte[] bytes = ByteBufUtil.getBytes(byteBuf);
        Map jsonMap = JsonHelper.deserialize(bytes, Map.class);

        CommandFrame frame = convertCommandFrame(session, command, jsonMap);
        out.add(frame);
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, CommandFrame frame, List<Object> out) {
        TcpJsonPacket packet = new TcpJsonPacket(frame);
        byte[] bytes = packet.toByteArray();

        out.add(Unpooled.wrappedBuffer(bytes));
    }
}
